package com.lee.auth.security.context;

import com.lee.auth.security.token.TokenPayloadOuter.TokenPayload;
import lombok.AllArgsConstructor;

import static java.lang.Long.MIN_VALUE;
import static java.lang.System.currentTimeMillis;

/**
 * @author Lee HN
 * @date 2021/4/1 10:04
 */
@AllArgsConstructor(staticName = "of")
public class AuthContext {

    public final long userId;

    public final int[] authorities;

    public final String client;

    public final long expire;

    public final boolean expired;

    public boolean isAuthenticated() {
        return !(userId == MIN_VALUE || expired);
    }

    public static final AuthContext ANONYMOUS = new AuthContext(MIN_VALUE, null, null, 0L, false);

    public static AuthContext of(TokenPayload payload) {
        return payload == null ? null : new AuthContext(payload.getId(), payload.getAuthorities(),
                payload.getClient(), payload.getExpire(), payload.getExpire() < currentTimeMillis());
    }

}
